use std::{fmt::Display, time::SystemTime};

use e_utils::{chrono, cmd::{Cmd, ExeType}};

// 定义泛型函数用于跨平台同步系统时间
pub fn sync_systemtime<T: Into<SystemTime> + Display>(time: T) -> e_utils::AnyResult<()> {
    let sys_time: SystemTime = time.into();
    #[cfg(target_os = "windows")]
    {
        let dt = chrono::DateTime::<chrono::Local>::from(sys_time);
        let date_str = dt.format("%Y-%m-%d").to_string();
        let time_str = dt.format("%H:%M:%S").to_string();

        // 设置日期
        let date_output = Cmd::new("date").set_type(ExeType::Cmd).args(&[date_str]).output()?;
        if !date_output.status.success() {
            return Err("Failed to set system date on Windows".into());
        }

        // 设置时间
        let time_output = Cmd::new("time").set_type(ExeType::Cmd).args(&[time_str]).output()?;
        if !time_output.status.success() {
            return Err("Failed to set system time on Windows".into());
        }
    }
    #[cfg(target_os = "linux")]
    {
        let time_str = time.to_string();
        let output = Cmd::new("timedatectl")
            .args(&["set-time", &time_str])
            .output()?;
        if !output.status.success() {
            return Err("Failed to set system time on Linux".into());
        }
    }
    #[cfg(target_os = "macos")]
    {
        let time_str = time.to_string();
        let output = Cmd::new("date")
            .args(&["-u", "-s", &time_str])
            .output()?;
        if !output.status.success() {
            return Err("Failed to set system time on macOS".into());
        }
    }
    Ok(())
}
